<template>
  <div>
    <el-dialog class="dialog" :visible.sync="visible" :width="width" :modal-append-to-body="false" :show-close="true"
      :close-on-click-modal="false" :before-close="hide" :style="{ '--el-dialog-height': height }">
      <template slot="title">
        <div class="close" @click="hide"></div>
        <div class="dialog-header">
          <div class="header-title">{{ params.activityId ? '修改' : '新增' }} 慰问品活动</div>
        </div>
      </template>
      <div class="dialog-body">
        <div class="form-box">
          <el-form ref="formRef" class="formStyle" :model="form" :rules="formRules" label-width="85px"
            @submit.native.prevent>
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="form.activityName" placeholder="请输入慰问品活动名称" :spellcheck="false" />
            </el-form-item>
            <el-form-item label="封面" prop="imageUrl">
              <el-upload el-upload ref="uploadRef" class="upload" action="#" with-credentials :auto-upload="false"
                list-type="picture-card" :limit="1" :file-list="uploadFileList" accept=".jpg,.jpeg,.png"
                :http-request="handleFileUpload" :on-remove="handleRemove" :on-change="handleChange"
                :on-exceed="handleExceed" :on-success="handleSuccess">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="领取时间" prop="startTime">
              <el-date-picker v-model="timeArr" type="daterange" unlink-panels range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd" clearable />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入描述" :spellcheck="false" :rows="3"
                resize="none" />
            </el-form-item>
            <el-form-item label="规格" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格" :spellcheck="false" />
            </el-form-item>
            <el-form-item label="最大领取数" prop="maxLimit">
              <el-input-number v-model="form.maxLimit" placeholder="请输入最大领取数" :min="1" controls-position="right"
                :spellcheck="false" />
            </el-form-item>
            <el-form-item label="支持邮寄" prop="supportMail">
              <el-switch v-model="form.supportMail" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hide">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getFileNameFromURL } from '@/utils/index.js';
import * as api from '@/api/condolenceManger/index.js';
import * as fileApi from '@/api/file/index.js';

export default {
  name: 'GiftEditDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    params: {
      type: Object,
      default: {},
    },
    width: {
      type: String,
      default: '80%',
    },
    height: {
      type: String,
      default: '915px',
    },
  },
  data() {
    return {
      dataLoading: false,
      form: {},
      formRules: {
        activityName: [{ required: true, trigger: 'blur', message: '请输入慰问品活动名称' }],
        startTime: [{ required: true, trigger: 'blur', message: '请选择领取时间' }],
        description: [{ required: true, trigger: 'blur', message: '请输入描述' }],
      },
      timeArr: [],
      uploadFileList: [],
    };
  },
  watch: {
    visible: {
      handler(value) {
        if (value) {
          this.form = this.getForm();
          this.getData();
        }
      },
      immediate: true,
    },
    timeArr: {
      handler(value) {
        this.form.startTime = `${value[0]} 00:00:00`;
        this.form.endTime = `${value[1]} 23:59:59`;
      },
      immediate: true,
    },
  },
  methods: {
    hide() {
      this.resetForm();
      this.$emit('update:visible', false);
    },
    resetForm() {
      this.form = this.getForm();
      this.uploadFileList = [];
      this.timeArr = [];
    },
    getForm() {
      let form = {
        activityName: '',
        imageUrl: '',
        startTime: '',
        endTime: '',
        description: '',
        specification: '',
        maxLimit: 1,
        supportMail: 0,
        status: 1,
      };
      return form;
    },
    getData() {
      if (!this.params.collectId) return;
      api.getGiftInfo(this.params.collectId).then(({ data }) => {
        Object.keys(this.form).forEach((key) => {
          if (data[key] !== undefined) this.form[key] = data[key];
        });
        this.uploadFileList = [{ name: getFileNameFromURL(this.form.imageUrl), url: this.form.imageUrl }];
        this.timeArr = [this.form.startTime, this.form.endTime];
      });
    },
    // 移除文件时移除文件时
    handleRemove(file, fileList) {
      this.uploadFileList = fileList;
    },
    // 文件状态改变
    handleChange(file, fileList) {
      if (file.status == 'ready') {
        this.uploadFileList = fileList;
      }
    },
    // 当超出限制时
    handleExceed(files, fileList) {
      this.$message.warning({
        message: `当前限制选择 1 个图片，已经选择了 ${fileList.length} 个图片`,
      });
    },
    // 上传文件方法
    async handleFileUpload(param) {
      const formData = new FormData();
      formData.append('file', param.file);
      try {
        const data = await fileApi.uploadPictureMinio(formData);
        param.onSuccess(data);
      } catch (error) {
        console.log('error', error);
        param.onError();
      }
    },
    // 上传文件成功
    async handleSuccess(data, file, file_list) {
      if (!data) return;
      try {
        this.form.imageUrl = data.url;
        // 提交表单
        let funcName = '';
        if (this.params.collectId) {
          funcName = 'editGift';
          this.form.collectId = this.params.collectId;
        } else {
          funcName = 'addGift';
        }
        const res = await api[funcName]({ ...this.form });
        this.$message.success({ message: res.msg });
        this.$emit('success', 'GiftEditDialog');
        this.hide();
      } catch (error) {
        console.log('error', error);
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;
        try {
          const text = this.params.collectId ? `是否确定修改？` : `是否确定新增`;
          await this.$confirm(text, '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          });
          for (const key in this.form) {
            if (typeof this.form[key] == 'undefined') this.form[key] = '';
          }
          // 提交上传
          if (this.uploadFileList.length && this.uploadFileList.some((file) => file.status == 'ready')) {
            await this.$refs.uploadRef.submit();
          } else {
            // 提交表单
            let funcName = '';
            if (this.params.collectId) {
              funcName = 'editGift';
              this.form.collectId = this.params.collectId;
            } else {
              funcName = 'addGift';
            }
            const res = await api[funcName]({ ...this.form });
            this.$message.success({ message: res.msg });
            this.$emit('success', 'GiftEditDialog');
            this.hide();
          }
        } catch (error) {
          console.log('error', error);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/dialog.scss';
// @import '@/assets/styles/mixin.scss';

// ::v-deep .el-dialog__body {
//   padding-right: 5px !important;
// }

.dialog-body {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.formStyle {
  // @include el-form-style;
  ::v-deep .el-form-item {
    width: 100%;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0px;
      // .el-form-item__content {
      //   text-align: center;
      // }
    }

    // .el-input-number {
    //   width: auto !important;
    // }

    .unit {
      margin-left: 10px;
    }
    .el-upload-list--picture-card .el-upload-list__item {
      width: 222px;
      height: auto;
      line-height: 1;
    }
  }
}
</style>
